package admin

import (
	"bbs-go/internal/models"
	"bbs-go/internal/models/constants"
	"bbs-go/internal/pkg/errs"
	"bbs-go/internal/services"
	"strconv"

	"github.com/kataras/iris/v12"
	"github.com/mlogclub/simple/web"
	"github.com/mlogclub/simple/web/params"
)

type UserDepartmentController struct {
	Ctx iris.Context
}

func (c *UserDepartmentController) GetBy(id int64) *web.JsonResult {
	t := services.UserDepartmentService.Get(id)
	if t == nil {
		return web.JsonErrorMsg("Not found, id=" + strconv.FormatInt(id, 10))
	}
	return web.JsonData(t)
}

func (c *UserDepartmentController) AnyList() *web.JsonResult {
	list, paging := services.UserDepartmentService.FindPageByParams(params.NewQueryParams(c.Ctx).LikeByReq("name").PageByReq().Asc("sort_no").Asc("id"))
	return web.JsonData(&web.PageResult{Results: list, Page: paging})
}

func (c *UserDepartmentController) GetDepartmentList() *web.JsonResult {
	user := services.UserTokenService.GetCurrent(c.Ctx)
	if user == nil {
		return web.JsonError(errs.NotLogin)
	}
	userId := 0
	if user.HasAnyRole(constants.RoleOwner) {
		userId = 0
	} else if user.HasAnyRole(constants.RoleAdmin) {
		userId = int(user.Id)
	}
	list, err := services.UserDepartmentService.FindDepartmentList(userId)
	if err != nil {
		return web.JsonError(err)
	}
	return web.JsonData(list)
}

func (c *UserDepartmentController) PostCreate() *web.JsonResult {
	t := &models.UserDepartment{}
	err := params.ReadForm(c.Ctx, t)
	if err != nil {
		return web.JsonError(err)
	}

	err = services.UserDepartmentService.Create(t)
	if err != nil {
		return web.JsonError(err)
	}
	return web.JsonData(t)
}

func (c *UserDepartmentController) PostUpdate() *web.JsonResult {
	id, err := params.FormValueInt64(c.Ctx, "id")
	if err != nil {
		return web.JsonError(err)
	}
	t := services.UserDepartmentService.Get(id)
	if t == nil {
		return web.JsonErrorMsg("entity not found")
	}

	err = params.ReadForm(c.Ctx, t)
	if err != nil {
		return web.JsonError(err)
	}

	err = services.UserDepartmentService.Update(t)
	if err != nil {
		return web.JsonError(err)
	}
	return web.JsonData(t)
}
